
import Axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
import Qs from 'qs';
import Cookie from '../../editor/framework/net/cache/Cookie';
import { getBaseURL } from './BaseURL';



export class Request {

    private intance: AxiosInstance = null;

    constructor(config: AxiosRequestConfig) {
        this.intance = Axios.create(config);

        this.intance.interceptors.request.use((config: AxiosRequestConfig): AxiosRequestConfig => {

            config.headers.Authorization = Cookie.getCookies('token');

            const configProps = config || {}
            configProps.params = config.params ? config.params : {}

            let params = config.data || undefined

            if (config.headers['Content-Type'] == 'multipart/form-data') {
                params = Qs.stringify(params);
            }
            else {
                params = params ? JSON.stringify(params) : ''

            }

            return config;
        },
            (error) => Promise.reject(error));

        this.intance.interceptors.response.use((response) => {
            let resdata = response.data;
            let code = resdata["code"] ? resdata["code"] : 200;

            if (code != 200) {
                if (code == 100009) {
                    // return LoginUtil.emptyToken();
                }

                if (code == 100019) {
                    // return LoginUtil.emptyToken();
                }

                return Promise.reject(resdata["message"]);
            }

            return response.data;
        },
            (error) => {
                let respone = error.response;
                return Promise.reject(respone.data.message)
            });
    }

    request(config: AxiosRequestConfig) {
        return this.intance.request(config);
    }
}

const baseURL = getBaseURL();

const RequestIntance: Request = new Request({
    baseURL: baseURL,

    timeout: 60000, // 请求超时 60s
});

export default RequestIntance;